package server.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import server.demo.dto.ApiResponse;
import server.demo.entity.Payment;
import server.demo.service.PaymentService;

import java.util.List;

@RestController
@RequestMapping("/api/v1/payments")
@CrossOrigin(origins = "*")
public class PaymentController {
    
    @Autowired
    private PaymentService paymentService;
    
    @PostMapping("/process")
    public ApiResponse<String> processPayment(
            @RequestParam Long orderId,
            @RequestParam String paymentMethod) {
        try {
            Payment payment = paymentService.processPayment(orderId, paymentMethod);
            return ApiResponse.success("付款成功", "订单已成功付款，交易号：" + payment.getTransactionId());
        } catch (Exception e) {
            return ApiResponse.error("付款失败: " + e.getMessage());
        }
    }
    
    @PostMapping("/refund/{orderId}")
    public ApiResponse<Payment> processRefund(
            @PathVariable Long orderId,
            @RequestParam(required = false) String refundReason) {
        try {
            Payment refund = paymentService.processRefund(orderId, refundReason);
            return ApiResponse.success("退款处理成功", refund);
        } catch (Exception e) {
            return ApiResponse.error("退款处理失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/order/{orderId}")
    public ApiResponse<List<Payment>> getPaymentsByOrderId(@PathVariable Long orderId) {
        try {
            List<Payment> payments = paymentService.getPaymentsByOrderId(orderId);
            return ApiResponse.success(payments);
        } catch (Exception e) {
            return ApiResponse.error("获取付款记录失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/user/{userId}")
    public ApiResponse<List<Payment>> getPaymentsByUserId(@PathVariable Long userId) {
        try {
            List<Payment> payments = paymentService.getPaymentsByUserId(userId);
            return ApiResponse.success(payments);
        } catch (Exception e) {
            return ApiResponse.error("获取付款记录失败: " + e.getMessage());
        }
    }
}